package io.gitee.xjt2016.modules.security;


import com.google.common.base.Preconditions;
import io.gitee.xjt2016.modules.service.sys.UserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Log4j2
@Component
public class LoginFilter implements Filter {
    public static final String excludeUrl = "(/static/*.*)|(/login.*)|(/logout.*)|(/demo.*)";

    public static final String COOKIE_KEY = "token";
    public static final int COOKIE_EXPIRE_TIME = 60 * 60 * 24;

    @Value(value = "${login.session.timeout:86400}")
    private int sessionTimeOut = COOKIE_EXPIRE_TIME;

    @Autowired
    UserService userService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        String requestURI = req.getRequestURI();
        if (!requestURI.matches(excludeUrl)) {
            try {
                Preconditions.checkArgument(userService.checkLogin(req), "登录状态校验失败");
            } catch (Throwable throwable) {
                res.sendRedirect("/login");
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
